package tum0r.data.serialize;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 工程: TestSerialize<br>
 * 包: tum0r.data.serialize<br>
 * 创建者: tum0r<br>
 * 创建时间: 2020/8/23 09:09<br>
 * <br>
 */
public class Deserialize {
    public static <T> T deserialize(String data, Class<T> c) {
        JSONObject temp = new JSONObject();
        temp.put("value", data);
        return deserialize(data, c);
    }

    public static <T> T deserialize(JSONObject data, Class<T> c) {
        T result = null;
        try {
            if (c != null) {
                result = c.getDeclaredConstructor().newInstance();
                if (List.class.isAssignableFrom(c)) {
                    for (int i = 0; ; i++) {
                        String key = String.valueOf(i);
                        if (data.containsKey(key)) {
                            List<?> temp = (List<?>) result;
//                            temp.add(deserialize(data.getJSONObject(key),c.componentType()));
                        } else {
                            break;
                        }
                    }
                } else if (Set.class.isAssignableFrom(c)) {
                    for (int i = 0; ; i++) {
                        String key = String.valueOf(i);
                        if (data.containsKey(key)) {
                            ((Set) result).add(data.get(key));
                        } else {
                            break;
                        }
                    }
                } else {
                    LinkedList<Field> fields = Reflect.getFields(c);
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (data.containsKey(fieldName)) {
                            Class<?> fieldClass = field.getType();
                            if (List.class.isAssignableFrom(fieldClass) || Set.class.isAssignableFrom(fieldClass)) {

                            }
                        }
                    }
                }
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return result;
    }
}
